package com.example.module.dialog;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;

public class PasscodeTextWatcher implements TextWatcher {
	private PasscodeText myPasscode;
	private PasscodeText prevPasscode;
	private PasscodeText nextPasscode;
	private PasscodeTextListener passcodeTextListener;
	
	public interface PasscodeTextListener {
		public void onSetPasscode();
	}
	
	public PasscodeTextWatcher(PasscodeText prevPasscode, PasscodeText myPasscode, PasscodeText nextPasscode, PasscodeTextListener passcodeTextListener) {
		this.prevPasscode = prevPasscode;
		this.myPasscode = myPasscode;
		this.nextPasscode = nextPasscode;
		this.passcodeTextListener = passcodeTextListener;
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		Log.d("PasscodeTextWatcher.onTextChanged", s.toString());
	}

	@Override
	public void afterTextChanged(Editable s) {
		Log.d("PasscodeTextWatcher.afterTextChanged", s.toString());
		
		if (s != null && s.toString().length() == 1) {
			if (nextPasscode != null)
				nextPasscode.requestFocus();
			
			if (myPasscode != null) {
				myPasscode.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						if (passcodeTextListener != null)
							passcodeTextListener.onSetPasscode();		
					}
				}, 500);
			}
		}
	}

	public void onKeyDown(Editable s, int keyCode, KeyEvent event) {
		Log.d("PasscodeTextWatcher.onKeyDown", "s=" + s.toString() + " keyCode=" + keyCode + " event=" + event + " KEYCODE_BACK=" + KeyEvent.KEYCODE_BACK);
		
		if ((s == null || s.toString().isEmpty()) && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
			if (prevPasscode != null) {
				prevPasscode.setText("");
				prevPasscode.requestFocus();	
			}
		}
	}

	public PasscodeTextListener getPasscodeTextListener() {
		return passcodeTextListener;
	}

	public void setPasscodeTextListener(PasscodeTextListener passcodeTextListener) {
		this.passcodeTextListener = passcodeTextListener;
	}
}
